package cn.kgc.mybatis;

import cn.kgc.mybatis.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
 * @author: 课工场
 * @since 2023/9/21
 * 演示使用mybatis框架实现数据的crud操作
 */
public class MybatisOperation {

    private SqlSessionFactory factory;

    @Before
    public void init() throws Exception {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    }

    //  查询数据列表
    @Test
    public void selectAll() {
        // sqlSession
        SqlSession sqlSession = factory.openSession();
        List<User> users = sqlSession.selectList("a.selectAll");
        System.out.println("users = " + users);
    }

    // 查询单个数据
    @Test
    public void selectOne() throws Exception {

        SqlSession sqlSession = factory.openSession();
        User user = sqlSession.selectOne("a.selectOne", 7);
        System.out.println("user = " + user);
    }

    // 添加一个用户信息
    @Test
    public void addOne() throws Exception {

        SqlSession sqlSession = factory.openSession();
        User user = new User();
        user.setUsername("jack2");
        user.setPassword("123456");
        user.setAge(25l);

        System.out.println("user = " + user);

        // 影响的行数
        int line = sqlSession.insert("a.addOne", user);
        System.out.println("line = " + line);
        // 提交事务
        sqlSession.commit();
        System.out.println("user = " + user);
        sqlSession.close();
    }


    @Test
    public void updateOne() throws Exception {

        SqlSession sqlSession = factory.openSession();
        User user = new User();
        user.setUsername("杰克");
        user.setId(12L);

        int line = sqlSession.update("a.updateOne", user);
        System.out.println("line = " + line);
        // 提交事务
        sqlSession.commit();
        sqlSession.close();


    }

    // 删除数据
    @Test
    public void deleteOne() throws Exception {
        SqlSession sqlSession = factory.openSession();
        int delete = sqlSession.delete("a.deleteOne", 12);
        System.out.println("delete = " + delete);
        sqlSession.commit();
        sqlSession.close();
    }

}
